package game.network
{
	import away3d.containers.*;
	
	import engine.asset.*;
	import engine.core.*;
	import engine.graphics.vfx.*;
	import engine.math.*;
	import engine.network.*;
	import engine.social.*;
	
	import flash.events.*;
	import flash.net.*;
	import flash.utils.*;
	
	import game.*;
	import game.actor.*;
	import game.asset.*;
	import game.core.*;
	import game.messages.login.*;
	import game.messages.party.*;
	import game.messages.progression.*;
	import game.messages.quest.*;
	import game.messages.simulation.*;
	import game.quest.*;
	import game.scene.*;
	import game.store.*;
	import game.ui.core.*;
	
	public class RxSimulation
	{
		private static var s_sentHistory:Array;
		private static var s_simulationStarted:Boolean;
		private static var s_actorLookup:Dictionary;
		private static var s_actorIdReverseLookup:Dictionary;
		private static var s_sendViewerMessageTimeAccumulator:Number;
		private static var s_viewerMessageQueue:Array;
		private static var s_viewerGameTime:Number;
		private static var s_viewerSimGameTime:Number;
		private static var s_joinData:RxSimulation_JoinResponse;
		private static var s_loadingStateMachine:RxStateMachine;
		private static var s_mapSelectedMessage:RxSimulation_MapSelected;
		public static var s_sequenceNumber:uint;
		private static var s_inputSequenceNumber:uint;
		private static var s_heroInitData:Vector.<Object>;
		private static var s_mapSelectedCallback:Function;
		private static var s_server:RxTransactionServer;
		private static var s_loginCallback:Function;
		private static var s_lastReceiveTime:Number;
		private static const s_undefinedNode:int = 65535;
		private static var s_defaultLoginNet:String = null;
		private static var s_defaultLoginId:String = null;
		private static var m_loginNetwork:String;
		private static var m_loginUserName:String;
		private static var s_findServerComplete:Boolean;
		
		public function RxSimulation()
		{
		}
		
		public static function Initialize(server:RxTransactionServer) : void
		{
			s_server = server;
			/*
			s_server.AddListener(RxQuest_QuestUpdateMessage.messageId, QueueViewerMessage);
			s_server.AddListener(RxSimulation_CreateActorMessage.messageId, QueueViewerMessage);
			s_server.AddListener(RxSimulation_ActivatePortalMessage.messageId, QueueViewerMessage);
			s_server.AddListener(RxSimulation_ActorAuraUpdate.messageId, QueueViewerMessage);
			s_server.AddListener(RxSimulation_ActorStateMessage.messageId, QueueViewerMessage);
			s_server.AddListener(RxSimulation_ActorHealthUpdateMessage.messageId, QueueViewerMessage);
			s_server.AddListener(RxSimulation_PlayerEnergyUpdateMessage.messageId, QueueViewerMessage);
			s_server.AddListener(RxSimulation_PlayerTimersUpdate.messageId, QueueViewerMessage);
			s_server.AddListener(RxSimulation_QueueAttackMessage.messageId, QueueViewerMessage);
			s_server.AddListener(RxSimulation_ItemPickupResponseMessage.messageId, QueueViewerMessage);
			s_server.AddListener(RxSimulation_CurrencyUpdateMessage.messageId, OnCurrencyUpdate);
			s_server.AddListener(RxSimulation_CurrencyDrop.messageId, OnCurrencyDrop);
			s_server.AddListener(RxSimulation_PlayerLeftMessage.messageId, QueueViewerMessage);
			s_server.AddListener(RxParty_GotInvite.messageId, OnPartyGotInviteMessage);
			s_server.AddListener(RxParty_PlayerJoined.messageId, OnPartyPlayerJoined);
			s_server.AddListener(RxParty_PlayerLeft.messageId, OnPartyPlayerLeft);
			s_server.AddListener(RxProgression_NextServer.messageId, OnNextServer);
			*/
			s_sentHistory = new Array();
			s_simulationStarted = false;
			s_actorLookup = new Dictionary();
			s_actorIdReverseLookup = new Dictionary();
			s_sendViewerMessageTimeAccumulator = 0;
			s_viewerMessageQueue = new Array();
			s_viewerGameTime = 0;
			s_viewerSimGameTime = 0;
			s_joinData = new RxSimulation_JoinResponse();
			s_joinData.playerIndex = -1;
			s_loadingStateMachine = null;
			s_mapSelectedMessage = null;
			s_sequenceNumber = 0;
			s_inputSequenceNumber = 0;
			s_heroInitData = new Vector.<Object>;
			s_mapSelectedCallback = null;
			s_lastReceiveTime = getTimer();
		}
		
		public static function GetPlayerIndex() : int
		{
			return s_joinData.playerIndex;
		}
		
		public static function SendPlayerImmunityRequest(param1:Boolean) : void
		{
			
		}
		
		public static function Update(param1:Number, param2:View3D, param3:RxGameCamera) : void
		{
			var _loc_4:int = 0;
			var _loc_5:Object = null;
			var _loc_6:RxNetMessageBase = null;
			var _loc_8:RxHero = null;
			var _loc_9:XML = null;
			var _loc_10:String = null;
			var _loc_11:Number = NaN;
			var _loc_12:Number = NaN;
			var _loc_13:int = 0;
			if (s_loadingStateMachine != null)
			{
				s_loadingStateMachine.Update(param1);
				return;
			}
			if (!s_simulationStarted)
			{
				return;
			}
			var _loc_7:Number = 0.18;
			s_sendViewerMessageTimeAccumulator = s_sendViewerMessageTimeAccumulator + param1;
			if (s_sendViewerMessageTimeAccumulator > _loc_7)
			{
				s_sendViewerMessageTimeAccumulator = 0;
				_loc_4 = 0;
				while (_loc_4 < s_viewerMessageQueue.length)
				{
					
					_loc_5 = s_viewerMessageQueue[_loc_4];
					_loc_6 = _loc_5 as RxNetMessageBase;
					OnMessageToViewer(_loc_6, param2, param3);
					_loc_4++;
				}
				s_viewerMessageQueue.length = 0;
			}
			if (s_viewerGameTime != 0)
			{
				s_viewerGameTime = s_viewerGameTime + param1;
			}
			_loc_4 = 0;
			while (_loc_4 < s_heroInitData.length)
			{
				
				_loc_5 = s_heroInitData[_loc_4];
				_loc_8 = _loc_5["hero"];
				if (!_loc_8.WasConfigured() && _loc_8.IsConfigured())
				{
					_loc_9 = _loc_5["entityXML"];
					_loc_10 = _loc_5["entitySpawner"];
					_loc_11 = _loc_5.hasOwnProperty("health") ? (_loc_5["health"]) : (-1);
					_loc_12 = _loc_5.hasOwnProperty("healthMax") ? (_loc_5["healthMax"]) : (-1);
					_loc_13 = _loc_5.hasOwnProperty("spawnNode") ? (_loc_5["spawnNode"]) : (-1);
					s_heroInitData.splice(_loc_4, 1);
					_loc_4 = _loc_4 - 1;
					//_loc_8.InitializeHero(param2, param3, _loc_9, _loc_10, _loc_13);
					//_loc_8.InitializeHealth(_loc_11, _loc_12);
					if (_loc_8.GetPlayerIndex() == s_joinData.playerIndex)
					{
						param3.SetTarget(_loc_8);
					}
				}
				_loc_4++;
			}
		}
		
		private static function OnMessageToViewer(param1:RxNetMessageBase, param2:View3D, param3:RxGameCamera) : void
		{
			/*
			var _loc_4:RxActor = null;
			var _loc_5:RxHero = null;
			var _loc_6:RxHeroLocal = null;
			var _loc_7:RxActorState = null;
			var _loc_8:RxItem = null;
			var _loc_9:RxPortal = null;
			var _loc_10:RxSimulation_ActivatePortalMessage = null;
			var _loc_11:RxSimulation_ActorStateMessage = null;
			var _loc_12:RxSimulation_QueueAttackMessage = null;
			var _loc_13:RxActor = null;
			var _loc_14:RxSimulation_ActorHealthUpdateMessage = null;
			var _loc_15:RxSimulation_ActorTeamChangeMessage = null;
			var _loc_16:RxSimulation_ActorBuffUpdate = null;
			var _loc_17:RxSimulation_ItemPickupResponseMessage = null;
			var _loc_18:RxQuest_QuestUpdateMessage = null;
			var _loc_19:Vector.<RxEntity> = null;
			var _loc_20:RxInventory_UseInventoryItemResponse = null;
			var _loc_21:RxSimulation_PlayerImmunityTimerMessage = null;
			var _loc_22:RxSimulation_PlayerLevelUpMessage = null;
			var _loc_23:int = 0;
			var _loc_24:int = 0;
			var _loc_25:RxMessage_PickupResponse = null;
			switch(param1.GetId())
			{
				case RxSimulation_ActivatePortalMessage.messageId:
				{
					_loc_10 = param1 as RxSimulation_ActivatePortalMessage;
					_loc_9 = s_actorLookup[_loc_10.actorId] as RxPortal;
					if (_loc_9)
					{
						_loc_9.SetActivated();
					}
					break;
				}
				case RxSimulation_CreateActorMessage.messageId:
				{
					OnCreateActorMessage(param1 as RxSimulation_CreateActorMessage, param2, param3);
					break;
				}
				case RxSimulation_ActorStateMessage.messageId:
				{
					_loc_11 = param1 as RxSimulation_ActorStateMessage;
					_loc_7 = s_actorLookup[_loc_11.actorId] as RxActorState;
					if (_loc_7)
					{
						_loc_23 = _loc_11.node0 != s_undefinedNode ? (_loc_11.node0) : (-1);
						_loc_24 = _loc_11.node1 != s_undefinedNode ? (_loc_11.node1) : (-1);
						_loc_4 = s_actorLookup[_loc_11.targetId] as RxActor;
						_loc_7.ReceiveState(_loc_11, _loc_23, _loc_24, _loc_4, _loc_11.inputSequenceNumber);
					}
					break;
				}
				case RxSimulation_PlayerTimersUpdate.messageId:
				{
					_loc_6 = RxHeroLocal.FindPlayer();
					if (_loc_6)
					{
						_loc_6.HandleTimersUpdate(param1 as RxSimulation_PlayerTimersUpdate);
					}
					break;
				}
				case RxSimulation_QueueAttackMessage.messageId:
				{
					_loc_12 = param1 as RxSimulation_QueueAttackMessage;
					_loc_13 = s_actorLookup[_loc_12.attackingActorId] as RxActor;
					if (_loc_13 != null)
					{
						_loc_13.ReceiveQueueAttackMessage(_loc_12);
					}
					else if (_loc_12.thornsEffect == 0)
					{
						RxActor.CommitAttack(_loc_12);
					}
					break;
				}
				case RxSimulation_ActorHealthUpdateMessage.messageId:
				{
					_loc_14 = param1 as RxSimulation_ActorHealthUpdateMessage;
					_loc_4 = s_actorLookup[_loc_14.actorId] as RxActor;
					if (_loc_4 != null)
					{
						_loc_4.ReceiveActorHealthUpdateMessage(_loc_14);
					}
					break;
				}
				case RxSimulation_ActorTeamChangeMessage.messageId:
				{
					_loc_15 = param1 as RxSimulation_ActorTeamChangeMessage;
					_loc_4 = s_actorLookup[_loc_15.actorId] as RxActor;
					if (_loc_4 != null)
					{
						_loc_4.SetTeam(_loc_15.team);
					}
					break;
				}
				case RxSimulation_ActorBuffUpdate.messageId:
				{
					_loc_16 = param1 as RxSimulation_ActorBuffUpdate;
					_loc_7 = s_actorLookup[_loc_16.actorId] as RxActorState;
					if (_loc_7 != null)
					{
						_loc_7.ReceiveBuffUpdateMessage(_loc_16);
					}
					break;
				}
				case RxSimulation_PlayerEnergyUpdateMessage.messageId:
				{
					_loc_6 = RxHeroLocal.FindPlayer();
					if (_loc_6)
					{
						_loc_6.HandleEnergyUpdateMessage(param1 as RxSimulation_PlayerEnergyUpdateMessage);
					}
					break;
				}
				case RxSimulation_ItemPickupResponseMessage.messageId:
				{
					_loc_17 = param1 as RxSimulation_ItemPickupResponseMessage;
					_loc_8 = s_actorLookup[_loc_17.actorId] as RxItem;
					if (_loc_8)
					{
						_loc_25 = new RxMessage_PickupResponse(_loc_17.response);
						_loc_8.QueueMessage(_loc_25);
					}
					break;
				}
				case RxQuest_QuestUpdateMessage.messageId:
				{
					_loc_18 = param1 as RxQuest_QuestUpdateMessage;
					RxQuestManager.HandleQuestUpdateMessage(_loc_18);
					_loc_19 = RxEntity.FindByType(RxEntityType.ENTITY_TYPE_ITEM);
					for each (_loc_8 in _loc_19)
					{
						
						_loc_8.OnQuestUpdateMessage(_loc_18);
					}
					break;
				}
				case RxSimulation_PlayerLeftMessage.messageId:
				{
					OnPlayerLeftMessage(param1 as RxSimulation_PlayerLeftMessage);
					break;
				}
				case RxInventory_UseInventoryItemResponse.messageId:
				{
					_loc_20 = param1 as RxInventory_UseInventoryItemResponse;
					_loc_5 = RxHero.FindPlayerByIndex(_loc_20.playerIndex);
					if (_loc_5)
					{
						_loc_5.HandleUseInventoryItemResponse(_loc_20);
					}
					break;
				}
				case RxSimulation_PlayerImmunityTimerMessage.messageId:
				{
					_loc_21 = param1 as RxSimulation_PlayerImmunityTimerMessage;
					_loc_5 = RxHero.FindPlayerByIndex(_loc_21.playerIndex);
					if (_loc_5)
					{
						_loc_5.HandleImmunityTimerMessage(_loc_21);
					}
					break;
				}
				case RxSimulation_PlayerLevelUpMessage.messageId:
				{
					_loc_22 = param1 as RxSimulation_PlayerLevelUpMessage;
					_loc_5 = RxHero.FindPlayerByIndex(_loc_22.playerIndex);
					if (_loc_5)
					{
						_loc_5.HandleLevelUpMessage(_loc_22);
					}
					break;
				}
				default:
				{
					break;
				}
			}*/
		}
		
		
		public static function IsLoggingIn() : Boolean
		{
			return s_loadingStateMachine != null;
		}
		
		public static function SetNextMap(param1:String) : void
		{
			RxLog.Info("set next map: " + param1);
			var _loc_2:* = new RxProgression_SetMapName();
			_loc_2.mapName = param1;
			RxTransactionServer.instance.SendMessage(_loc_2);
		}
		
		public static function BeginLoading(param1:Function, param2:Boolean) : void
		{
			var _loc_4:String = null;
			var _loc_5:String = null;
			s_loginCallback = param1;
			var _loc_3:Boolean = false;
			if (param2)
			{
				if (RxClientVars.StringExists("ssUrl") && RxClientVars.StringExists("ssPort"))
				{
					_loc_4 = RxClientVars.GetString("ssUrl");
					_loc_5 = RxClientVars.GetString("ssPort");
					s_server.SetServerAddress(_loc_4, parseInt(_loc_5));
				}
				if (RxClientVars.StringExists("deploymentUrl"))
				{
					_loc_3 = true;
				}
			}
			s_loadingStateMachine = new RxStateMachine();
			s_loadingStateMachine.AddState("findServer", FindServerState, false);
			s_loadingStateMachine.AddState("identifyUser", IdentifyUserState, false);
			s_loadingStateMachine.AddState("login", LoginState, false);
			s_loadingStateMachine.AddState("joinGame", JoinGameState, false);
			s_loadingStateMachine.AddState("done", DoneLoadingState, false);
			if (_loc_3)
			{
				s_loadingStateMachine.ChangeState("findServer");
			}
			else
			{
				s_loadingStateMachine.ChangeState("identifyUser");
			}
		}
		
		private static function DoneLoadingState(param1:String, param2:Number) : void
		{
			switch(param1)
			{
				case "enter":
				{
					if (s_joinData.playerIndex < 0)
					{
						s_joinData.playerIndex = 0;
					}
					RxStore.instance.RetrieveStoreFromServer(null);
					break;
				}
				case "update":
				{
					if (s_mapSelectedMessage != null)
					{
						s_server.SendMessage(s_mapSelectedMessage);
						s_mapSelectedMessage = null;
					}
					s_loadingStateMachine = null;
					if (s_loginCallback != null)
					{
						s_loginCallback();
						s_loginCallback = null;
					}
					break;
				}
				default:
				{
					break;
				}
			}
		}
		
		private static function JoinGameState(param1:String, param2:Number) : void
		{
			var _loc_3:RxLogin_JoinRequest = null;
			switch(param1)
			{
				case "enter":
				{
					RxLog.Info("send join request");
					RxNetIDManager.instance.Reset();
					s_server.AddListener(RxSimulation_JoinResponse.messageId, OnJoinResponse);
					_loc_3 = new RxLogin_JoinRequest();
					_loc_3.sessionId = RxClientVars.GetString("joinSession");
					s_server.SendMessage(_loc_3);
					break;
				}
				case "update":
				{
					break;
				}
				case "exit":
				{
					break;
				}
				default:
				{
					break;
				}
			}
		}
		
		private static function OnJoinResponse(param1:RxNetMessageBase) : void
		{
			s_joinData = RxSimulation_JoinResponse(param1);
			s_loadingStateMachine.ChangeState("done");
		}
		
		private static function LoginState(param1:String, param2:Number) : void
		{
			switch(param1)
			{
				case "enter":
				{
					s_server.Open(m_loginNetwork, m_loginUserName);
					break;
				}
				case "update":
				{
					if (s_server.IsConnecting())
					{
						break;
					}
					if (!s_server.IsConnected())
					{
						RxLog.Warning("couldn\'t log in");
						s_loadingStateMachine.ChangeState("done");
						RxMaster.ShowLoginErrorAlert("System Error", "Failed to connect to the game server.  Refresh the browser to try again.", "ui/portraits/system_message_network_down.png");
						break;
					}
					if (s_server.IsLoggedIn())
					{
						s_loadingStateMachine.ChangeState("joinGame");
						break;
					}
					break;
				}
				case "exit":
				{
					break;
				}
				default:
				{
					break;
				}
			}
		}
		
		private static function IdentifyUserState(param1:String, param2:Number) : void
		{
			var _loc_3:String = null;
			switch(param1)
			{
				case "enter":
				{
					if (s_defaultLoginNet != null && s_defaultLoginId != null)
					{
						m_loginNetwork = s_defaultLoginNet;
						m_loginUserName = s_defaultLoginId;
						s_loadingStateMachine.ChangeState("login");
					}
					// changed for jobin
					s_loadingStateMachine.ChangeState("login");
					break;
				}
				case "update":
				{
					if (RxSocial.instance.IsLoggedIn())
					{
						m_loginNetwork = RxSocial.instance.GetNetworkId();
						_loc_3 = RxSocial.instance.GetUserId();
						if (_loc_3 != "uservar")
						{
							m_loginUserName = _loc_3;
						}
						s_loadingStateMachine.ChangeState("login");
					}
					break;
				}
				case "exit":
				{
					break;
				}
				default:
				{
					break;
				}
			}
		}
		
		private static function FindServerState(_arg1:String, _arg2:Number) : void
		{
			var deployment:String;
			var url:String;
			var gameId:String;
			var gameSecret:String;
			var query:String;
			var urlRequest:URLRequest;
			var urlLoader:URLLoader;
			var onLoaded:Function;
			var method:String = _arg1;
			var deltaTime:Number = _arg2;
			switch (method)
			{
				case "enter":
					s_findServerComplete = false;
					deployment = "itvm602";
					if (RxClientVars.StringExists("deploymentName")){
						deployment = RxClientVars.GetString("deploymentName");
					};
					url = RxClientVars.GetString("deploymentUrl");
					gameId = "4407e9bd675f17bc11e9d7f8f7002e89";
					gameSecret = gameId;
					query = "http://" + url + "/cdreplat1/rapiLive/gameServer/list?game=" + gameId + "&secret=" + gameSecret + "&_pretty=true&_decode=true";
					urlRequest = new URLRequest(query);
					urlLoader = new URLLoader();
					onLoaded = function (_arg1:Event) : void{
						var _local2:String;
						var _local4:Object;
						var _local5:int;
						var _local6:int;
						var _local7:Object;
						var _local8:String;
						s_findServerComplete = true;
						var _local3:int = 9001;
						if (_arg1.eventPhase == 2)
						{
							_local4 = JSON.parse(_arg1.target.data);
							_local5 = _local4.objects.length;
							_local6 = 0;
							while (_local6 < _local5) 
							{
								_local7 = _local4.objects[_local6];
								if (_local7.deployment.fullName != deployment)
								{
								} 
								else 
								{
									_local8 = _local7.serverNode.fullName;
									if (_local8 == "default")
									{
										_local2 = s_server.GetURL();
									} 
									else 
									{
										if (_local8.indexOf(".") < 0 && !_local8 == "localhost")
										{
											_local2 = (_local8 + ".cdrentertainment.com");
										} 
										else 
										{
											_local2 = _local8;
										}
									}
									_local3 = _local7.startPort;
									break;
								}
								_local6++;
							}
						}
						s_server.SetServerAddress(_local2, _local3);
					}
					urlLoader.addEventListener(Event.COMPLETE, onLoaded, false, 0, true);
					urlLoader.load(urlRequest);
					break;
				case "update":
					if (s_findServerComplete)
					{
						s_loadingStateMachine.ChangeState("identifyUser");
					}
					break;
				case "exit":
					break;
			}
		}
		
		public static function WaitMapSelected(param1:Function) : void
		{
			RxLog.Info("wait map selected");
			s_mapSelectedCallback = param1;
			s_server.AddListener(RxSimulation_MapSelected.messageId, OnMapSelected);
			SendMapSelected(RxProgression_Constants.s_defaultMapName);
		}
		
		private static function OnMapSelected(param1:RxNetMessageBase) : void
		{
			var _loc_2:* = param1 as RxSimulation_MapSelected;
			RxLog.Info("on map selected: " + _loc_2.mapName);
			if (s_mapSelectedCallback != null)
			{
				s_mapSelectedCallback(_loc_2.mapName);
				s_mapSelectedCallback = null;
				s_server.RemoveListener(RxSimulation_MapSelected.messageId, OnMapSelected);
			}
		}
		
		public static function SendMapSelected(param1:String) : void
		{
			var _loc_2:* = new RxSimulation_MapSelected();
			_loc_2.mapName = param1;
			if (s_loadingStateMachine == null)
			{
				s_server.SendMessage(_loc_2);
			}
			else
			{
				s_mapSelectedMessage = _loc_2;
			}
		}
		
		public static function EndLoading() : void
		{
			s_simulationStarted = true;
			s_server.SendMessage(new RxSimulation_MapLoaded());
		}
	}
}